import React, { useState, useMemo, useEffect } from 'react';
import { InfoDlg, Title, cline, ColView, filter_list, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, show_mt, uDb, uJob,
    get_umt, trim_data, KFile, HandView, BtTxt, PanelFind, Btn, is_empty, loc } from 'sui';
import { get_title, reload, get_ck, fix_col, load_tech_col, tech_mod, psn_mod } from './cmd';
import { fix_psn } from 'task/cmd';
import { useAccess } from 'cache';
import { DlgBuy } from './ctl';

const TechView = ({ mod }) => {
    const [open_info, openInfo] = useState(false);
    const [open_buy, openBuy] = useState(false);
    const [main, setMain] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const [no_acc, is_acc] = useAccess();
    const umd = useCmd();

    useEffect(() => {
        load_tech_col(setCol, mod);
        reload(null, mod, setMain);
    }, [mod]);

    const getRow = useMemo(() => {
        const lst = filter_list(["sn", "name"], col);
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter, col]);

    const hreturn = () => {
        load_tech_col(setCol, mod);
        umd.hreturn();
    };

    const hModify = (url, v, h) => {
        umd.startWait();

        const cmd = {
            ...v,
            line: cline(),
        };

        uDb(null, url, cmd,
            r => {
                reload(umd.endWait, mod, setMain);
                if (h) {
                    h();
                }
            },
            e => {
                umd.setErr();
                setMain(null);

                if (h) {
                    h();
                }
            }
        )
    };

    const act = {
        "add": (v, h) => hModify("tech/add", { v: { ...v, tp: mod } }, h),
        "edit": (v, h) => hModify("tech/md", { v: [v] }, h),
        "buy": (v) => {
            umd.startWait();

            uJob(null, "sale/order",
                {
                    line: cline(),
                    v: v,
                },
                r => {
                    umd.endWait();
                    openInfo(true);
                },
                e => umd.setErr());
        }
    };

    const pact = {
        "buy": () => openBuy(true),
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: tech_mod(mod), name: loc("l_605"), fix: fix_col()},
            {sn: psn_mod(mod), name: loc("l_688"), fix: fix_psn()},
        ];

        return <ColView hreturn={hreturn} title={loc("l_320")} subtitle={loc("l_221")} list={list} cur={tech_mod(mod)}/>;
    }

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];

        col.forEach(d => {
            if (d.sn === "mt") {
                d.ctl = [
                    {sn: "T", name: get_umt("T")},
                    {sn: "G", name: get_umt("G")},
                ];
                d.ctp = "list";
            }

            ret.push(d);
        });

        return ret;
    };

    if (umd.isFin("edit") || umd.isFin("add")) {
        return <HandView umd={umd} title={loc("l_177")} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const hImport = (val) => {
        if (is_empty(col)) {
            alert(loc("l_686"));
            return;
        }

        if (is_empty(val)) {
            alert(loc("l_276"));
            return;
        }

        trim_data(val, ["sn", "name"]);
        val.forEach(d => d["tp"] = mod);

        umd.update("tech/madd", {v: val});
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 130, export: false, formatter: props => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(null, d, "edit")} disabled={no_acc("ac")}>{loc("l_235")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "buy")} disabled={no_acc("ad")}>{loc("l_552")}</BtTxt>
                    </div>
                );
            }},
        ];

        col.forEach(d => show_mt(tmp, d, 126));

        return tmp;
    };

    const getList = () => {
        if (is_empty(col)) {
            return null;
        }

        return col.map(d => d.sn);
    };

    const rowTempl = () => {
        const tmp = getList();
        if (is_empty(tmp)) {
            return null;
        }

        const v = {};
        tmp.forEach(k => v[k] = "1");

        return [v];
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn className="mr-4" hcmd={() => umd.pact(null, null, "col")} disabled={no_acc("ab")}>{loc("l_221")}</Btn>
            <KFile umd={umd} title={loc("l_177")} col={getList()} row={rowTempl()} hcmd={hImport} no_acc_in={no_acc("ac")}/>
            <Btn color="green" hcmd={() => umd.pact(null, null, "add")} className="ml-3" disabled={no_acc("af")}>{loc("l_239")}</Btn>
        </div>
    );

    const Left = () => <Title sub={get_title(mod)}>{loc("l_177")}</Title>;

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={getCol()} row={getRow} high={high} gref={umd.gref}/>
            <DlgBuy open={open_buy} setOpen={openBuy} hcmd={v => umd.act(act, v)} cur={umd.cur} is_acc={is_acc}/>
            <InfoDlg open={open_info} setOpen={openInfo} msg={loc("l_562")}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {TechView};
